package com.power.sifa.respond.service.impl;

import com.plf.core.common.service.BaseServiceImpl;
import com.power.sifa.respond.dao.Apl_plaintiffDao;
import com.power.sifa.respond.model.Apl_plaintiff;
import com.power.sifa.respond.model.pageInfo.Apl_plaintiffPageInfo;
import com.power.sifa.respond.service.Apl_plaintiffService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.List;

/**
 *  原告业务层实现
 */
@Service
public class Apl_plaintiffServiceImpl extends BaseServiceImpl implements Apl_plaintiffService {

    @Autowired
    private Apl_plaintiffDao dao;

    @Override
    public Apl_plaintiff getById(Serializable id) {
        return dao.findById(id).orElse(null);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveOrUpdate(Apl_plaintiff apl_plaintiff) {
    	// save 如果数据库不存在这条数据，就会执行保存（即将这条数据插入到数据库）；如果数据库存在这条数据，就会根据主键去更新这条数据
        if (apl_plaintiff.getPrimaryKey() != null) {
        	 Apl_plaintiff apl_plaintifffDb = dao.findById(apl_plaintiff.getPrimaryKey()).orElse(null);
             if(apl_plaintifffDb != null) {
                BeanUtils.copyProperties(apl_plaintiff, apl_plaintifffDb);
                dao.save(apl_plaintifffDb);
                return;
             }
        }
        dao.save(apl_plaintiff);
    }

    @Override
    public void removeById(Serializable id) {
        dao.deleteById(id);
    }

    @Override
    public Page<Apl_plaintiff> findAll(Apl_plaintiffPageInfo pageInfo) {
        //排序等定义
        Sort sort;
        if("asc".equals(pageInfo.getOrder())) {
            sort = Sort.by(Sort.Direction.ASC, pageInfo.getSort());
        }else {
            sort = Sort.by(Sort.Direction.DESC, pageInfo.getSort());
        }
        //分页的定义
        Pageable pageable = PageRequest.of(pageInfo.getPageNumber()<=1 ? 0 : pageInfo.getPageNumber()-1, pageInfo.getPageSize(), sort);
        //查询条件
        Specification spec = this.createSpecification(pageInfo);
        return dao.findAll(spec, pageable);
    }

    @Transactional(rollbackFor = Exception.class)
    public void removeByIds(List<Integer> ids) {
        dao.removeByIds(ids);
    }

    @Override
	public List<Apl_plaintiff> findAll() {
		return dao.findAll();
	}

	@Override
	public void saveAll(List<Apl_plaintiff> list) {
		dao.saveAll(list);
	}
}
